package com.yiwu.web.controller;

import com.yiwu.common.aspect.ApiOperationLog;
import com.yiwu.common.aspect.ApiVerifyLogin;
import com.yiwu.common.exception.BaseResponse;
import com.yiwu.common.model.vo.favorite.FavoritePageReqVO;
import com.yiwu.common.model.vo.favorite.FavoritePageRspVO;
import com.yiwu.common.model.vo.product.ProductReqVO;
import com.yiwu.common.utils.ResultUtil;
import com.yiwu.web.service.UserFavoritesService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.yiwu.common.utils.EncryptionUtil.getUserToken;


/**
 * @version 1.0
 * @description TODO
 * @date 2024/5/25 19:36
 */
@RestController
@RequestMapping("/favor")
public class FavoriteController {

    @Resource
    private UserFavoritesService userfavoritesService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperationLog
    @PostMapping("/add")
    @Operation(summary = "添加收藏")
    @ApiVerifyLogin
    public BaseResponse<Boolean> addFavorite(@RequestBody ProductReqVO productReqVO, HttpServletRequest request) {
        Long userId = getUserToken(request);
        Boolean res = userfavoritesService.addFavorite(productReqVO,userId);
        String favoriteCount = stringRedisTemplate.opsForValue().get(userId + "yiwu-favoriteCount");
        if(favoriteCount != null){
            stringRedisTemplate.opsForValue().set(userId + "yiwu-favoriteCount", String.valueOf((Integer.parseInt(favoriteCount)+1)));
        }
        return ResultUtil.success(res);
    }

    @PostMapping("/cancel")
    @Operation(summary = "移除收藏")
    @ApiVerifyLogin
    public BaseResponse<Boolean> cancelFavorite(@RequestBody ProductReqVO productReqVO, HttpServletRequest request) {
        Long userId = getUserToken(request);
        Boolean res = userfavoritesService.cancelFavorite(productReqVO,userId);
        String favoriteCount = stringRedisTemplate.opsForValue().get(userId + "yiwu-favoriteCount");
        if(favoriteCount != null){
            stringRedisTemplate.opsForValue().set(userId + "yiwu-favoriteCount", String.valueOf((Integer.parseInt(favoriteCount)-1)));
        }
        return ResultUtil.success(res);
    }

    @PostMapping("/list")
    @Operation(summary = "查看用户收藏的商品")
    @ApiVerifyLogin
    public BaseResponse<List<FavoritePageRspVO>> getFavoriteList(@RequestBody FavoritePageReqVO favoritePageReqVO, HttpServletRequest request){
        Long userId = getUserToken(request);
        List<FavoritePageRspVO> res = userfavoritesService.getFavoriteList(favoritePageReqVO,userId);
        return ResultUtil.success(res);
    }


}
